<!-- 动态表单设置组件 -->
<template>
  <div class="setUpForm" id="setUpForm">
    <div class="left">
      <LeftConfig
        :layout="layout"
        @layoutChange="emit('update:layout', $event)"
        @tabChange="tabChange"
        :businessType="businessType"
        :tab-list="tablist"
        :upData="upData1"
        :subCode="subCode"
      />
    </div>
    <div class="center">
      <a-tabs
        lazy-load
        @change="(e)=>changeTabs(e as string)"
        position="left"
        type="text"
        v-if="showCenterData?.length !== 0"
        style="height: 100%"
      >
        <a-tab-pane
          style="border-radius: 15px"
          v-for="(item, index) in showCenterData"
          :key="item.subCode"
        >
          <template #title>
            <div class="title" v-if="!item?.isEdit">
              <span>{{ item.cnName }}</span>
              <div>
                <icon-edit @click="Edit(item)" style="padding: 0 10px" />
                <icon-delete @click="del(index, item.id)" style="color: red" />
              </div>
            </div>
            <div class="title" v-else>
              <a-input
                @blur="blur(item)"
                v-model="item.cnName"
                allow-clear
                style="width: 150px"
              />
              <icon-edit @click="blur(item)" style="padding-left: 10px" />
            </div>
            <div
              v-if="index === showCenterData.length - 1"
              style="
                display: flex;
                justify-content: center;
                margin: 20px 0;
                color: #7a7676;
                height: 100%;
              "
              @click="add"
            >
              <icon-plus :size="18" />
            </div>
          </template>
          <CenterConfig
            style="height: 100%"
            @choiceComponent="choiceComponent"
            :choiceUuid="(componentObj.data.uuid as string)"
            v-model:setUpList="item.componentList"
            :layout="layout"
            :businessType="businessType"
            :updata="upData"
          />
        </a-tab-pane>
      </a-tabs>
      <!-- <CenterConfig
        v-else
        @choiceComponent="choiceComponent"
        :choiceUuid="(componentObj.data.uuid as string)"
        v-model:setUpList="copySetUpList"
        :layout="layout"
        :businessType="businessType"
        :updata="upData"
      /> -->
    </div>
    <div class="right">
      <RightDrawer
        ref="rightDrawer"
        v-model:componentObj="componentObj.data"
        @componentObjChange="componentObjChange"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { isJSON } from '@/utils/isType';
import { useSetupFormStore } from '@/store';
import LeftConfig from './components/LeftConfig/index.vue';
import CenterConfig from './components/CenterConfig/index.vue';
import clonedeep from 'lodash.clonedeep';
import RightDrawer from './components/RightDrawer/index.vue';
import * as config from '../setupConfig';
// import { Control } from '@/api/control/type';
import { tabList, componentList } from '../setupConfig';

const store = useSetupFormStore();
const props = withDefaults(
  //参数说明
  defineProps<{
    layout: string; //a-form的layout属性
    businessType?: string | string[];
    setUpData?: any[]; // 控件数据
    optionData?: any;
    sliceName?: string; // 去除具体子集名称（例如组织基本信息，传入组织，只保留后面的基本信息）
  }>(),
  {}
);

const centerData = reactive<{ data: any }>({ data: [] });
const tabCode = ref('baseComponent');
const businessCode = ref('');
const subCode = ref('');

const emit = defineEmits(['update:layout', 'changeSeconds']);
// 左侧列表
const tablist: any = ref([]);
// 初始化控件
const init = async () => {
  if (props.businessType && Array.isArray(props.businessType)) {
    props.businessType.forEach((ele) => {
      if (ele !== 'baseComponent') {
        businessCode.value = ele;
      }
    });
  } else if (props.businessType) {
    businessCode.value = props.businessType;
  }
  if (props.setUpData) return;
  if (!props.businessType) return;
  tablist.value = await config.init(props.businessType);
  centerData.data = clonedeep(
    tablist.value.map((ele: any) =>
      clonedeep(changeCenterData(ele, props.optionData))
    )
  );
  if (tabCode.value === 'baseComponent' && centerData.data.length) {
    tabCode.value = centerData.data[0].code;
  }
  centerData.data[0].componentList?.forEach((item) => {
    item?.componentList?.forEach((sub) => {
      sub.props = sub.props.length ? JSON.parse(sub.props) : void 0;
      sub?.childrenCtl?.forEach((talCtl) => {
        talCtl.props = talCtl.props.length ? JSON.parse(talCtl.props) : void 0;
      });
    });
  });
  emit('changeSeconds', centerData.data);
};
const Edit = (item: any) => {
  item.isEdit = true;
};
const add = () => {
  if (props.setUpData && props.setUpData[0]?.id) {
    const newData = clonedeep(props.setUpData);
    newData.push({
      subCode: 'sub' + +new Date(),
      name: '',
      componentList: []
    });
    subCode.value = newData.subCode;
    emit('changeSeconds', newData);
  } else {
    const newData = {
      subCode: 'sub' + +new Date(),
      name: '',
      componentList: []
    };
    centerData?.data[0]?.componentList.push(newData);
    subCode.value = newData.subCode;
    emit('changeSeconds', centerData.data);
  }
};

const del = (index: number, id: undefined | number) => {
  if (props.setUpData && props.setUpData[0]?.id) {
    const newData = clonedeep(props.setUpData);
    newData.splice(index, 1);
    store.addCollectionsIds(id as number);
    emit('changeSeconds', newData);
  } else {
    centerData?.data[0]?.componentList.splice(index, 1);
    emit('changeSeconds', centerData.data);
  }
};
watch(
  () => props.setUpData,
  (val) => {
    if (val) {
      centerData.data = clonedeep(val);
      subCode.value = subCode.value === '' ? val[0].subCode : subCode.value;
    } else {
      init();
    }
    // props.setUpData ? (centerData.data = clonedeep(props.setUpData)) : init();
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.optionData,
  () => {
    init();
  }
);
// 处理初始化控件数据
const changeCenterData = (data: any, prop?: any) => {
  const newData: any = {
    name: data.name,
    code: data.code,
    componentList: []
  };
  if (data.tabchildren) {
    data.tabchildren.forEach((ele: any) => {
      ele.tabcomponentList.forEach((item: any) => {
        item.subCode = ele.tabchildrencode;
      });
      newData.componentList.push({
        cnName: ele.tabchildrcnName,
        enName: ele.tabchildrenName,
        subCode: ele.tabchildrencode,
        componentList: [...ele.tabcomponentList]
      });
    });
  }
  if (prop) {
    prop.forEach((data: any) => {
      const { fieldName, props, option } = data;
      newData.forEach((ele: any) => {
        ele.componentList.forEach((item: any) => {
          if (item.fieldName === fieldName) {
            if (item.prop) {
              if (isJSON(item.props) && item.props) {
                const newProps = JSON.parse(item.props);
                newProps.option = props;
                item.props = JSON.stringify(newProps);
              }
            } else {
              item.props.option = JSON.stringify(props);
            }
          }
        });
      });
    });
  }
  return newData;
};
// 处理显示的控件数据
const showCenterData = computed(() => {
  props?.setUpData?.forEach((item) => {
    item?.componentList?.forEach((sub) => {
      sub?.componentList?.forEach((ctlItem) => {
        ctlItem?.childrenCtl?.forEach((tableChi) => {
          tableChi.ctlCnName = tableChi.cnName;
          tableChi.ctlComponentType = tableChi.componentType;
        });
      });
    });
  });
  if (props.setUpData && props.setUpData[0]?.id) {
    return props.setUpData;
  }
  if (centerData?.data?.length !== 0) {
    const newArr = centerData?.data?.find(
      (ele: any) => ele.code === tabCode.value
    )?.componentList;
    if (newArr) {
      if (!subCode.value) subCode.value = newArr[0]?.subCode;
      return newArr;
    } else {
      return centerData?.data;
    }
  } else {
    return [];
  }
});

// 点击跳转子集（多个子集才需要）
const tabChange = (e: string) => {
  if (e === 'baseComponent' && centerData.data?.length) {
    tabCode.value = centerData.data[0].code;
  } else {
    tabCode.value = e;
  }
};

// init();
const copySetUpList: any = ref([]);

//组件设置的参数
const componentObj = reactive<{ data: any }>({ data: {} });
const rightDrawer = ref(); //获取rightDrawer元素
//点击组件被选中时
const choiceComponent = (element: any) => {
  componentObj.data = element;
  rightDrawer.value.visible = true;
};
//组件被设置时
const componentObjChange = (data: any) => {
  if (props.setUpData && props.setUpData[0]?.id) {
    console.log('====================================1111111');
    console.log(data, centerData.data, props.setUpData);
    console.log('====================================');
    const newData = clonedeep(props.setUpData);
    newData.forEach((ele: any) => {
      if (ele.subCode === subCode.value) {
        ele.componentList.forEach((item: any) => {
          if (item.uuid === data.uuid) {
            for (let key in data) {
              item[key] = data[key];
            }
          }
        });
      }
    });
    upData(newData);
  } else {
    console.log(222, centerData.data, subCode.value);
    centerData.data.forEach((ele: any) => {
      if (ele.code === businessCode.value) {
        ele.componentList.forEach((item: any) => {
          if (item.subCode === subCode.value) {
            item.componentList.forEach((items: any) => {
              if (items.uuid === data.uuid) {
                for (let key in data) {
                  items[key] = data[key];
                }
              }
            });
          }
        });
      }
    });
    upData(centerData.data);
  }
};

const upData = (data: any) => {
  emit('changeSeconds', data);
};

const upData1 = () => {
  if (showCenterData.value[0].id) {
    emit('changeSeconds', showCenterData.value);
  } else {
    const newData = clonedeep(props.setUpData);
    newData[0].componentList = showCenterData.value;
    emit('changeSeconds', newData);
  }
};
const changeTabs = (e: string) => {
  subCode.value = e;
  console.log(e, 222, subCode.value);
};
const blur = (item: any) => {
  item.isEdit = false;
  upData1();
};
defineExpose({ copySetUpList, rightDrawer, init }); //抛出处理过后的列表
</script>

<style lang="less" scoped>
.setUpForm {
  // position: relative;
  display: flex;
  // align-items: center;
  justify-content: space-between;
  background: rgb(243, 243, 243);
  height: 100%;
  // width: 100%;
  min-width: 1000px;
  .left {
    // flex: 1;
    width: 250px;
    height: 100%;
    overflow: auto;
    // overflow: hidden;
  }
  .center {
    flex: 1;
    height: 100%;
    min-width: 350px;
    margin: 0 16px;
    overflow: auto;
  }
  .right {
    // overflow: auto;
    // background: #fff;
    // flex: 1;
    width: 300px;
    height: 100%;
    overflow: auto;
    // min-width: 350px;
    // position: relative;
  }
}
.title {
  // width: 100%;
  display: flex;
  justify-content: space-between;
  // background-color: #fff;
  // height: 50px;
  // width: 150px;
}
:deep(.arco-tabs-content) {
  background-color: #fff;
}
:deep(.arco-tabs-content-list) {
  height: 100%;
}
:deep(.arco-tabs-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}
:deep(.arco-tabs-content) {
  border-radius: 15px;
}
:deep(.arco-tabs-tab-title) {
  width: 100%;
  box-sizing: border-box;
  // padding: 0;
}
</style>
